package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.Share_Adapter;
import com.example.xianji.adapter.Value_Adapter;
import com.example.xianji.bean.NewsReplay;
import com.example.xianji.constant.Constant;
import com.example.xianji.single.Send_Contant;
import com.example.xianji.utils.Javascript;
import com.example.xianji.utils.MyWebViewClient;
import com.example.xianji.utils.SharesUtil;

import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.MyListview;

import com.example.xianji.eventbus.Replay_EventBus;
import com.example.xianji.widgets.X5WebView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.open.t.Weibo;
/*import com.tencent.mm.sdk.openapi.SendMessageToWX;
 import com.tencent.mm.sdk.openapi.WXMediaMessage;
 import com.tencent.mm.sdk.openapi.WXWebpageObject;*/
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author me
 * 新闻详情页面
 */
public class Main_news_detailsActivity extends Activity implements
        IWeiboHandler.Response {
    /******************** 新闻详情页面 ***************************/
    private ImageView imageview_news_share;
    private RelativeLayout news_details_back;

    private TextView news_details_title, news_details_tag, news_details_time,
            news_details_from, text_dian_zan, text_dian_cai;
    private X5WebView news_details_webview;
    //    private SharedPreferences sp;
//    private Editor ed;
    private LinearLayout layout2;
    private GridView province_gridview;
    private Share_Adapter mShare_Adapter;
    private PopupWindow show_popupWindow;
    //private ArrayList<Share> share_list = new ArrayList<Share>();

    private SsoHandler mSsoHandler;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private Oauth2AccessToken mAccessToken;

    private boolean isInstalledWeibo;
    private int supportApiLevel;
    private String news_share_url;
    private Weibo mWeibo;
    /**
     * 腾讯微博
     */
    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            mWeibo = new Weibo(Main_news_detailsActivity.this, XJApplication
                    .getTencent().getQQToken());
            if (ready(Main_news_detailsActivity.this)) {
                String content = news_details_title.getText().toString();
                mWeibo.sendText(content, new TQQApiListener("add_t", false,
                        Main_news_detailsActivity.this));
            }
        }
    };
    private String pic[];
    private MyListview news_replay_listview;// 回复新闻评论的楼主listview
    private EditText replay_details;
    private Button send_pinglun;
    private ArrayList<NewsReplay> reply_list = new ArrayList<NewsReplay>();// 楼主评论的集合
    private Value_Adapter mValue_Adapter;
    private int news_id;// 新闻id
    private int replay_dianji = 0;
    private LinearLayout linearlayout_news_praise, linearlayout_dian_cai;
    private int Praise = 0;//1为赞  2为踩
    private int praise_count, cai_count = 0;//点赞和踩 默认 为0
    private String news_content = "";
    private LinearLayout linearPraiseAndChai;
    @SuppressLint("JavascriptInterface")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    news_replay_listview.setAdapter(mValue_Adapter);
                    break;
                case 3:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main_news_details);
        /************* 初始化 **********************/
        init();
        if (getIntent().getIntExtra("news", 0) == 1) {
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    get_qiye_news_details();
                }
            });

        } else if (getIntent().getIntExtra("news", 0) == 2) {
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    get_news_details();
                }
            });
        }
        /********* 点击事件 **********************/
        ViewClick();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(Replay_EventBus event) {

        replay_dianji = event.getCount();
        if (event.getCount() == 1) {
            replay_details.setHint("回复:" + event.getName());
        } else if (event.getCount() == 2) {
            replay_details.setHint("回复:" + event.getName());
        }
    }

    private void init() {
        news_details_back = (RelativeLayout) findViewById(R.id.news_details_relative_back);
        news_details_title = (TextView) findViewById(R.id.news_details_title);
        news_details_tag = (TextView) findViewById(R.id.news_details_tag);
        news_details_time = (TextView) findViewById(R.id.news_details_time);
        news_details_from = (TextView) findViewById(R.id.news_details_from);
        imageview_news_share = (ImageView) findViewById(R.id.imageview_news_share);
        news_details_webview = (X5WebView) findViewById(R.id.news_details_webview);
        news_replay_listview = (MyListview) findViewById(R.id.news_replay_listview);
        replay_details = (EditText) findViewById(R.id.replay_details);
        send_pinglun = (Button) findViewById(R.id.send_pinglun);
        linearlayout_news_praise = (LinearLayout) findViewById(R.id.linearlayout_news_praise);
        linearlayout_dian_cai = (LinearLayout) findViewById(R.id.linearlayout_dian_cai);
        linearPraiseAndChai = (LinearLayout) findViewById(R.id.linearPraiseAndChai);
        text_dian_zan = (TextView) findViewById(R.id.text_dian_zan);
        text_dian_cai = (TextView) findViewById(R.id.text_dian_cai);
        mValue_Adapter = new Value_Adapter(Main_news_detailsActivity.this,
                reply_list);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        news_share_url = "http://m.xianjichina.com/news/details_"
                + getIntent().getStringExtra("news_details_id") + ".html";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if (requestCode == Constants.REQUEST_LOGIN
                || requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data,
                    loginListener);
        }
        /****************************** QQ 分享 必须加的，回调不起作用 ********************************/
        // 官方文档没这句代码, 但是很很很重要, 不然不会回调!
        Tencent.onActivityResultData(requestCode, resultCode, data,
                new Share_Listener());

        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE
                    || resultCode == Constants.REQUEST_QZONE_SHARE
                    || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, new Share_Listener());
            }
        }

    }

    private void ViewClick() {
        news_details_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main_news_detailsActivity.this.finish();
            }
        });

        imageview_news_share.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Photo_show();
                province_gridview.setAdapter(mShare_Adapter);
                show_popupWindow.showAtLocation(findViewById(R.id.news_detail),
                        Gravity.BOTTOM, 0, 0);

                province_gridview
                        .setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int position, long id) {
                                if (SharesUtil.getShareList().get(position).getName()
                                        .equals("微信好友")) {
                                    SharesUtil.weiXin_showShare(news_share_url, news_details_title.getText().toString());
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("微信朋友圈")) {
                                    SharesUtil.weiXin_prnyyouquan_showShare(news_share_url, news_details_title.getText().toString());
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("微信收藏")) {
                                    SharesUtil.weiXin_collection_showShare(news_share_url, news_details_title.getText().toString());
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("腾讯微博")) {
                                    tengxun_weibo_share();
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("新浪微博")) {
                                    WeiBo_share();
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("QQ")) {
                                    QQ_Share();
                                } else if (SharesUtil.getShareList().get(position).getName()
                                        .equals("QQ空间")) {
                                    share_QQ_Qzon();
                                }
                            }
                        });
            }
        });

        send_pinglun.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                XJApplication.cachThreadPool.execute(new Runnable() {

                    @Override
                    public void run() {
                        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                            send_data();//发送评论
                        } else {
                            Main_news_detailsActivity.this.startActivity(new Intent(Main_news_detailsActivity.this, Main_LoginActivity.class));
                        }
                    }
                });
            }
        });

        linearlayout_news_praise.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //点赞
                Praise = 1;
                if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                    Praise_News(Praise);
                } else {
                    PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, Contant.NewsToLogin);//从新闻详情页点赞到登录页面
                    startActivity(new Intent(Main_news_detailsActivity.this, Main_LoginActivity.class));

                }
            }
        });

        linearlayout_dian_cai.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Praise = 2;
                if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                    Praise_News(Praise);
                } else {
                    PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, Contant.NewsToLogin);//从新闻详情页点赞到登录页面
                    startActivity(new Intent(Main_news_detailsActivity.this, Main_LoginActivity.class));
                }
            }
        });
    }

    public void get_news_details() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("new_id",
                getIntent().getStringExtra("news_details_id"));
        httpUtils.send(HttpMethod.POST, Contant.news_details, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @SuppressLint("JavascriptInterface")
                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            if (object.getInt("status") == 1) {
                                final JSONObject obj = object
                                        .getJSONObject("data");
                                news_id = obj.getInt("id");

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        try {
                                            linearPraiseAndChai.setVisibility(View.VISIBLE);
                                            news_details_title.setText(obj
                                                    .getString("news_title"));
                                            news_details_tag.setText(obj
                                                    .getJSONObject("cname")
                                                    .getString("cat_name"));
                                            news_details_time.setText(obj
                                                    .getString("created_at"));
                                            praise_count = obj
                                                    .getInt("praise_count");
                                            cai_count = obj.getInt("tread_count");
                                            text_dian_zan.setText(praise_count + "");
                                            text_dian_cai.setText(cai_count + "");
                                            news_details_from
                                                    .setVisibility(View.VISIBLE);
                                            news_details_from.setText(obj
                                                    .getString("news_from"));

                                            news_content = obj.getString("news_content");
                                            news_details_webview
                                                    .loadDataWithBaseURL(
                                                            null,
                                                            news_content,
                                                            "text/html",
                                                            "utf-8", null);
                                            news_details_webview
                                                    .setWebViewClient(new MyWebViewClient(news_details_webview));
                                            /*
                                             * // 支持js
                                             * news_details_webview.getSettings
                                             * () .setJavaScriptEnabled(true);
                                             */
                                            // 设置本地调用对象及其接口
                                            news_details_webview
                                                    .addJavascriptInterface(
                                                            new Javascript(
                                                                    Main_news_detailsActivity.this),
                                                            "myObj");

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                                JSONArray replys_array = obj.getJSONArray("replys");
                                for (int i = 0; i < replys_array.length(); i++) {
                                    JSONObject replyObject = replys_array.getJSONObject(i);
                                    NewsReplay mReplay = new NewsReplay();
                                    mReplay.setAuthor(replyObject
                                            .getInt("author"));// 回复id
                                    mReplay.setAvatar(replyObject
                                            .getJSONObject("authors")
                                            .getString("avatar"));
                                    mReplay.setNews_id(replyObject
                                            .getInt("news_id"));
                                    mReplay.setNickname(replyObject
                                            .getJSONObject("authors")
                                            .getString("nickname"));
                                    mReplay.setArray(replyObject
                                            .getJSONArray("replys"));
                                    mReplay.setId(replyObject.getInt("id"));
                                    mReplay.setCreated_at(replyObject
                                            .getString("created_at"));
                                    mReplay.setDetails(replyObject
                                            .getString("details"));
                                    mReplay.setReply_id(replyObject
                                            .getInt("reply_id"));
                                    reply_list.add(mReplay);
                                }
                                handler.sendEmptyMessage(2);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void get_qiye_news_details() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("newid", getIntent().getStringExtra("news_details_id"));
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        httpUtils.send(HttpMethod.POST, Contant.qiye_news_details, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @SuppressLint("JavascriptInterface")
                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            if (object.getInt("status") == 1) {
                                final JSONObject obj = object
                                        .getJSONObject("data");
                                news_id = obj.getInt("id");
                                news_details_title.setText(obj
                                        .getString("news_title"));
                                news_details_tag.setText(obj.getJSONObject(
                                        "cname").getString("cat_name"));
                                news_details_time.setText(obj
                                        .getString("created_at"));
                                cai_count = obj.getInt("tread_count");
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            news_details_from.setVisibility(View.GONE);
                                            linearPraiseAndChai.setVisibility(View.VISIBLE);
                                            praise_count = obj.getInt("praise_count");
                                            text_dian_zan.setText(praise_count + "");
                                            text_dian_cai.setText(cai_count + "");
                                            news_details_webview
                                                    .loadDataWithBaseURL(
                                                            null,
                                                            obj.getString("news_content"),
                                                            "text/html",
                                                            "utf-8", null);
                                            // 支持js
                                            news_details_webview.getSettings()
                                                    .setJavaScriptEnabled(true);
                                            // 设置本地调用对象及其接口
                                            news_details_webview
                                                    .addJavascriptInterface(
                                                            new Javascript(
                                                                    Main_news_detailsActivity.this),
                                                            "myObj");
                                            news_details_webview
                                                    .setWebViewClient(new MyWebViewClient(news_details_webview));

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                                JSONArray replys_array = obj
                                        .getJSONArray("replys");
                                for (int i = 0; i < replys_array.length(); i++) {
                                    JSONObject replyObject = replys_array
                                            .getJSONObject(i);
                                    NewsReplay mReplay = new NewsReplay();
                                    mReplay.setAuthor(replyObject
                                            .getInt("author"));// 回复id
                                    mReplay.setAvatar(replyObject
                                            .getJSONObject("authors")
                                            .getString("avatar"));
                                    mReplay.setNews_id(replyObject
                                            .getInt("news_id"));
                                    mReplay.setNickname(replyObject
                                            .getJSONObject("authors")
                                            .getString("nickname"));
                                    mReplay.setArray(replyObject
                                            .getJSONArray("replys"));
                                    mReplay.setId(replyObject.getInt("id"));
                                    mReplay.setCreated_at(replyObject
                                            .getString("created_at"));
                                    mReplay.setDetails(replyObject
                                            .getString("details"));
                                    mReplay.setReply_id(replyObject
                                            .getInt("reply_id"));
                                    reply_list.add(mReplay);
                                }
                                handler.sendEmptyMessage(2);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /********************************** 发送评论数据接口 ***********************************************/
    public void send_data() {

        HashMap<String, Object> map = new HashMap<String, Object>();
        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
            map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        } else {
        }
        map.put("nid", news_id);// 新闻id
        map.put("details", replay_details.getText().toString());
        /**
         * 回复楼主 时点击时0,其余回复replay_dianji都是  2
         */
        if (replay_dianji == 0) {
            //	map.put("reply_user", Send_Contant.getInstance().getReplay_pinglun_id());
        }

        if (replay_dianji == 2) {
            map.put("reply_user", Send_Contant.getInstance()
                    .getReply_user());
            map.put("reply_id", Send_Contant.getInstance().getReplay_id());
        }
        JSONObject parmas = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.news_replay, parmas, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        Toast.makeText(Main_news_detailsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                        replay_details.setText("");
                        handler.sendEmptyMessage(3);
                    } else {
                        Toast.makeText(Main_news_detailsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void Praise_News(int praise) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("nid", news_id);// 新闻id
        map.put("dotype", praise);//1为赞  2为踩
        JSONObject parmas = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.news_praise, parmas, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        if (Praise == 1) {
                            //点赞
                            int total_praise = praise_count + 1;
                            text_dian_zan.setText(total_praise + "");
                        } else if (Praise == 2) {
                            //踩
                            int total_cai = cai_count + 1;
                            text_dian_cai.setText(total_cai + "");
                        }
                    } else {
                        Toast.makeText(Main_news_detailsActivity.this,
                                response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout2 = (LinearLayout) LayoutInflater.from(
                Main_news_detailsActivity.this).inflate(
                R.layout.province_popoupwindow_listview, null);
        province_gridview = (GridView) layout2
                .findViewById(R.id.province_gridview);
        if (mShare_Adapter == null) {
            mShare_Adapter = new Share_Adapter(this, SharesUtil.getShareList());
        }
        province_gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        if (show_popupWindow == null) {
            show_popupWindow = new PopupWindow(layout2,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
        }
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout2);
    }

    /**
     * QQ
     *
     * @return
     */
    public void QQ_Share() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
                QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "贤集网");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, news_details_title
                .getText().toString());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, news_share_url);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "贤集网");
        XJApplication.getTencent().shareToQQ(Main_news_detailsActivity.this,
                params, new Share_Listener());
    }

    public void share_QQ_Qzon() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
                QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "贤集网");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, news_details_title
                .getText().toString());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, news_share_url);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "贤集网");
        XJApplication.getTencent().shareToQQ(Main_news_detailsActivity.this,
                params, new Share_Listener());
    }

    private void tengxun_weibo_share() {
        XJApplication.getTencent().login(Main_news_detailsActivity.this, "all", loginListener);
    }

    /**
     * 腾讯微博
     */
    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                XJApplication.getTencent().setAccessToken(token, expires);
                XJApplication.getTencent().setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 腾讯微博是否登录
     *
     * @param context
     * @return
     */
    public boolean ready(Context context) {
        if (XJApplication.getTencent() == null) {
            return false;
        }
        boolean ready = XJApplication.getTencent().isSessionValid()
                && XJApplication.getTencent().getQQToken().getOpenId() != null;
        if (!ready) {
            Toast.makeText(context, "login and get openId first, please!",
                    Toast.LENGTH_SHORT).show();
        }
        return ready;
    }

    private void WeiBo_share() {
        mSsoHandler = new SsoHandler(Main_news_detailsActivity.this,
                XJApplication.mAuthInfo);
        mSsoHandler.authorizeClientSso(new AuthListener());
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(
                Main_news_detailsActivity.this, "4216978203");
        mWeiboShareAPI.registerApp();
        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        supportApiLevel = mWeiboShareAPI.getWeiboAppSupportAPI();
        mWeiboShareAPI.handleWeiboResponse(getIntent(),
                Main_news_detailsActivity.this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResp) {
        if (baseResp != null) {
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
                    Toast.makeText(this, "成功", Toast.LENGTH_LONG).show();
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
                    Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
                    Toast.makeText(this, "Error Message: " + baseResp.errMsg,
                            Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    private BaseMediaObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = news_details_title.getText().toString();
        mediaObject.description = "贤集网" + news_share_url;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.touxiang);
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = news_share_url;
        mediaObject.defaultText = "";
        return mediaObject;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, 0) == Contant.LoginToNews) {
            //如果登录过后就直接请求点赞数据
            Praise_News(Praise);
            PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        news_details_webview.destroy();
        news_details_webview = null;
        EventBus.getDefault().unregister(this);
    }

    /************************* QQ分享的回调接口 **************************************/
    public class Share_Listener implements IUiListener {
        @Override
        public void onError(UiError uiError) {
            Toast.makeText(Main_news_detailsActivity.this, uiError + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onComplete(Object arg0) {
            Toast.makeText(Main_news_detailsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_news_detailsActivity.this, "取消", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 腾讯微博
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                Toast.makeText(Main_news_detailsActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                Toast.makeText(Main_news_detailsActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                return;
            }
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {
        }

        @Override
        public void onError(UiError e) {
            Toast.makeText(Main_news_detailsActivity.this, e.errorDetail, Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_news_detailsActivity.this, "oncancle", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 腾讯微博
     *
     * @author me
     */
    private class TQQApiListener extends BaseUiListener {
        private String mScope = "all";
        private Boolean mNeedReAuth = false;
        private Activity mActivity;

        public TQQApiListener(String mScope, Boolean mNeedReAuth,
                              Activity mActivity) {
            super();
            this.mScope = mScope;
            this.mNeedReAuth = mNeedReAuth;
            this.mActivity = mActivity;
        }

        @Override
        public void onComplete(Object response) {
            final Activity activity = Main_news_detailsActivity.this;
            try {
                JSONObject json = (JSONObject) response;
                int ret = json.getInt("ret");
                if (ret == 0) {
                    Toast.makeText(Main_news_detailsActivity.this, "微博发送成功", Toast.LENGTH_SHORT).show();
                } else if (ret == 100030) {
                    if (mNeedReAuth) {
                        Runnable r = new Runnable() {
                            public void run() {
                                XJApplication.getTencent().reAuth(activity, mScope, new BaseUiListener());
                            }
                        };
                        Main_news_detailsActivity.this.runOnUiThread(r);
                    }
                } else if (ret == 6) {
                    Toast.makeText(Main_news_detailsActivity.this, "该账号未开通微博",
                            Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            try {
                // try catch 解决 调用这个对象出现空指针异常 （兼容问题）
                mAccessToken = Oauth2AccessToken.parseAccessToken(values);

                String phoneNum = mAccessToken.getPhoneNum();
                if (mAccessToken.isSessionValid()) {

                    if (isInstalledWeibo) {
                        if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                            if (supportApiLevel >= 10351 /*
                             * ApiUtils.
                             * BUILD_INT_VER_2_2
                             */) {
                                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                                weiboMessage.mediaObject = getWebpageObj();
                                SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                                request.transaction = String.valueOf(System
                                        .currentTimeMillis());
                                request.multiMessage = weiboMessage;
                                mWeiboShareAPI.sendRequest(
                                        Main_news_detailsActivity.this,
                                        request);
                            } else {
                                WeiboMessage weiboMessage = new WeiboMessage();
                                weiboMessage.mediaObject = getWebpageObj();
                                SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
                                request.transaction = String.valueOf(System
                                        .currentTimeMillis());
                                request.message = weiboMessage;
                                mWeiboShareAPI.sendRequest(
                                        Main_news_detailsActivity.this,
                                        request);
                            }
                        }
                    }
                    Toast.makeText(Main_news_detailsActivity.this, "授权成功",
                            Toast.LENGTH_SHORT).show();
                } else {
                    String code = values.getString("code");
                    Toast.makeText(Main_news_detailsActivity.this, "授权失败",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_news_detailsActivity.this, "取消",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(Main_news_detailsActivity.this,
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }
}
